<?php
//SALT:  md5(md5(pass) . username)
set_include_path("system:templates");

require_once('Template.php');
require_once('RedirectBrowserException.php');
require_once('oc.php');

$username = empty($_COOKIE['username']) ? '' : $_COOKIE['username'];
if ($username) {
	// already logged in... get out of here
	throw new RedirectBrowserException('index.php');
}

$error = false;

$action = empty($_POST['action']) ? '' : $_POST['action'];
if ($action == 'do_login') {
	$error = handle_login();
	if (!$error) {
		throw new RedirectBrowserException('index.php');
	}
}

$username = '';
if ($error) {
	$username = empty($_POST['username']) ? '' : $_POST['username'];
}


$tmpl = new Template();
$tmpl->login_error = $error;
$tmpl->login_username = $username;
$tmpl->loggedIn = false;

$loginHTML = $tmpl->build('login.tmpl');

$tmpl->pageContent = $loginHTML;

print $tmpl->build('page.tmpl');


function handle_login() {
	// function returns true for error, false for ok

	$username = empty($_POST['username']) ? '' : $_POST['username'];
	$password = empty($_POST['password']) ? '' : $_POST['password'];
	$procpass = md5(md5($password) . $username);
	echo 'tested with ' . $procpass . '<br />';
	if ($username == 'test' && $password == 'pass') {
		setcookie('username', $username);
		return false;  // success, no error
	}
	
	return true;  // error
}

?>